package 面试;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class phone implements Runnable{
    public synchronized void setSMS(){
        System.out.println(Thread.currentThread().getName()+"\tsetSMS");
        setEmail();
    }

    public synchronized void setEmail(){
        System.out.println(Thread.currentThread().getName()+"\tsetEmail");

    }

    public  void set(){
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\tset");
            get();
        }finally {
            lock.unlock();
        }
    }
    public  void get(){
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\tget");
        }finally {
            lock.unlock();
        }
    }

    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        set();
    }
}

public class ReenterLockDemo {

    public static void main(String[] args) {
        phone p = new phone();
        new Thread(() -> {
            p.setSMS();
        },"t1").start();

        new Thread(() -> {
            p.setSMS();
        },"t2").start();

        try { TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace(); }
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();

        Thread t3 = new Thread(p);
        Thread t4 = new Thread(p);
        t3.start();
        t4.start();
    }
}
